#include <Qt/qglobal.h>
#include "qbytearray.h"
#include "qstring.h"
#include "qvector.h"
#include "qt_windows.h"
#include "fecoremain.h"

QT_BEGIN_NAMESPACE

#if defined(Q_OS_WINCE)
extern void __cdecl qWinMain(HINSTANCE, HINSTANCE, LPSTR, int, int &, QVector<char *> &);
#else
extern void qWinMain(HINSTANCE, HINSTANCE, LPSTR, int, int &, QVector<char *> &);
#endif

QT_END_NAMESPACE

extern int fe_main(int, char **, PFESTARTER_CALLBACK);

int FeCoreMainInternal(HINSTANCE instance, HINSTANCE prevInstance, LPTSTR, int cmdShow,  PFESTARTER_CALLBACK callback)
{
	QByteArray cmdParam = QString::fromWCharArray(GetCommandLine()).toLocal8Bit();

#if defined(Q_OS_WINCE)
    wchar_t appName[MAX_PATH];
    GetModuleFileName(0, appName, MAX_PATH);
    cmdParam.prepend(QString(QLatin1String("\"%1\" ")).arg(QString::fromWCharArray(appName)).toLocal8Bit());
#endif

    int argc = 0;
    QVector<char *> argv(8);
    qWinMain(instance, prevInstance, cmdParam.data(), cmdShow, argc, argv);

#if defined(Q_OS_WINCE)
    wchar_t uniqueAppID[MAX_PATH];
    GetModuleFileName(0, uniqueAppID, MAX_PATH);
    QString uid = QString::fromWCharArray(uniqueAppID).toLower().replace(QLatin1String("\\"), QLatin1String("_"));

    // If there exists an other instance of this application
    // it will be the owner of a mutex with the unique ID.
    HANDLE mutex = CreateMutex(NULL, TRUE, (LPCWSTR)uid.utf16());
    if (mutex && ERROR_ALREADY_EXISTS == GetLastError()) {
        CloseHandle(mutex);

        // The app is already running, so we use the unique
        // ID to create a unique messageNo, which is used
        // as the registered class name for the windows
        // created. Set the first instance's window to the
        // foreground, else just terminate.
        // Use bitwise 0x01 OR to reactivate window state if
        // it was hidden
        UINT msgNo = RegisterWindowMessage((LPCWSTR)uid.utf16());
        HWND aHwnd = FindWindow((LPCWSTR)QString::number(msgNo).utf16(), 0);
        if (aHwnd)
            SetForegroundWindow((HWND)(((ULONG)aHwnd) | 0x01));
        return 0;
    }
#endif // Q_OS_WINCE

	int result = fe_main(argc, argv.data(), callback);
#if defined(Q_OS_WINCE)
    CloseHandle(mutex);
#endif
    return result;
}

FECORE_MAINPROC_EXPORT int WINAPI FeCoreMain(HINSTANCE hInstance, HINSTANCE hInstancePrev, LPTSTR args, int nCmdShow, PFESTARTER_CALLBACK callback)
{
	return FeCoreMainInternal(hInstance, hInstancePrev, args, nCmdShow, callback);
}


